<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }"
                >首页</el-breadcrumb-item
            >
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-alert
                title="注意：只允许为第三级分类设置相关参数！"
                type="warning"
                show-icon
                :closable="false"
            >
            </el-alert>
            <el-row class="cate-select">
                <el-col>
                    <span>请选择商品分类：</span>
                    <el-cascader
                        v-model="selectedKeys"
                        :options="cateList"
                        :props="cascaderProps"
                        @change="handleChange"
                        clearable
                    ></el-cascader>
                </el-col>
            </el-row>
            <!-- 标签页 -->
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" size="mini" :disabled="btnDisabled" @click="addParameter=true">添加参数</el-button>
                    <el-table :data="paramsData" border stripe>
                        <el-table-column label="明细" type="expand">
                            <template slot-scope="scope">
                                <!-- 循环渲染tag标签 -->
                                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(scope.row,i)">
                                    {{ item }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="序号" type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" icon="el-icon-edit" @click="selectParams(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>

                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" size="mini" :disabled="btnDisabled" @click="staticaddParameter = true">添加属性</el-button>
                    <el-table :data="paramsData" border stripe>
                        <el-table-column label="明细" type="expand">
                            <template slot-scope="scope">
                                <!-- 循环渲染tag标签 -->
                                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(scope.row,i)">
                                    {{ item }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="序号" type="index"></el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" size="mini" icon="el-icon-edit" @click="staticSelectParams(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" size="mini" icon="el-icon-delete" @click="staticremoveParams(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <!-- 添加动态参数 -->
                <el-dialog
						title="添加动态参数"
						:visible.sync="addParameter"
						width="50%"
					>
						<el-form
                            :model="addParameList"
							ref="addParamsRef"
							label-width="80px"
                            :rules="addFormParams"
						>
							<el-form-item label="动态参数" prop="attr_name" required>
								<el-input v-model="addParameList.attr_name"></el-input>
							</el-form-item>
						</el-form>
						<span slot="footer">
							<el-button @click="addParameter = false">取 消</el-button>
							<el-button type="primary" @click="addParameters()">确 定</el-button>
						</span>
				</el-dialog>
                <!-- 添加静态参数 -->
                <el-dialog
						title="添加静态参数"
						:visible.sync="staticaddParameter"
						width="50%"
					>
						<el-form
                            :model="staticaddParameList"
							ref="staticaddParamsRef"
							label-width="80px"
                            :rules="addFormParams"
						>
							<el-form-item label="静态参数" prop="attr_name" required>
								<el-input v-model="staticaddParameList.attr_name"></el-input>
							</el-form-item>
						</el-form>
						<span slot="footer">
							<el-button @click="staticaddParameter = false">取 消</el-button>
							<el-button type="primary" @click="staticaddParameters()">确 定</el-button>
						</span>
				</el-dialog>
                <!-- 修改动态参数 -->
                <el-dialog
                    title="修改动态参数"
                    :visible.sync="modifyParams"
                >
                    <el-form
                        :model="modifyForm"
                        :rules="addFormParams"
                        label-width="80px"
                        ref="modifyParamsRef"
                    >
                        <el-form-item label="动态参数" prop="attr_name" >
                            <el-input v-model="modifyForm.attr_name" autocomplete="off"></el-input>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
				        <el-button @click="modifyParams = false">取 消</el-button>
				        <el-button type="primary" @click="modifyParamsInfo()">确 定</el-button>
			        </div>
                </el-dialog>
                <!-- 修改静态参数 -->
                <el-dialog
                    title="修改静态参数"
                    :visible.sync="staticmodifyParams"
                >
                    <el-form
                        :model="staticmodifyForm"
                        :rules="addFormParams"
                        label-width="80px"
                        ref="staticmodifyParamsRef"
                    >
                        <el-form-item label="静态参数" prop="attr_name" >
                            <el-input v-model="staticmodifyForm.attr_name" autocomplete="off"></el-input>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
				        <el-button @click="staticmodifyParams = false">取 消</el-button>
				        <el-button type="primary" @click="staticmodifyParamsInfo()">确 定</el-button>
			        </div>
                </el-dialog>
            </el-tabs>
        </el-card>
    </div>
</template>
<script>
export default {
    data(){
        return{
            selectedKeys:[],
            cateList:[],
            cascaderProps:{
                expandTrigger:'hover',
                label:'cat_name',
                value:'cat_id',
                children:'children',
            },
            activeName:'many',
            paramsData:[],
            addParameter:false,
            addParameList:{
                attr_name:"",
                attr_sel:"many"
            },
            staticaddParameList:{
                attr_name:"",
                attr_sel:"only"
            },
            addFormParams:{
                attr_name:[
                    { required: true, message: "请输入参数名称", trigger: "blur" },
                ]
            },
            staticaddParameter:false,
            modifyParams:false,
            modifyForm:{},
            staticmodifyForm:{},
            staticmodifyParams:false,
        }
    },
    created() {
        this.getCateList()
    },
    methods:{
       async getCateList() {
           const { data: res } = await this.$http.get("categories");
           if(res.meta.status != 200){
               return this.$message.error("获取分类列表失败")
           }
           this.cateList=res.data;
       },
       handleChange(){
            this.getParamsData()
        },
        // 监听Tab的切换
        handleClick(){
            this.getParamsData()
        },
        async getParamsData(){
            // 判断是否选中三级分类
            if(this.selectedKeys.length != 3){
                return
            }
            
            const {data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,{
                params:{
                    sel:this.activeName
                }
            })
            if(res.meta.status != 200){
                return this.$message.error('获取参数列表失败')
            }

            // 对参数的明细进行处理：按空格拆为分数组
            res.data.forEach(item => {
                item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
            });

            console.log(res.data);

            // 判断是动态参数数据还是静态参数数据
            // if(this.activeName === 'many'){
            //     this.manyData = res.data
            // }else{
            //     this.onlyData = res.data
            // }
            this.paramsData = res.data
        },
        // 监听Tag的关闭事件，删除参数明细
        handleClose(row,i){
            row.attr_vals.splice(i,1)
            this.updateParamsDetail(row)
        },
        // 更新参数明细
        async updateParamsDetail(row){
            const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
                attr_name:row.attr_name,
                attr_sel:row.attr_sel,
                attr_vals:row.attr_vals.join(' ')
            })
            if(res.meta.status != 200){
                return this.$message.error('更新参数明细失败')
            }
            this.$message.success('更新参数明细成功')
        },
        //添加动态参数
        addParameters(){
            this.$refs.addParamsRef.validate(async valid =>{
                if (!valid) {
                    return this.$message.error("未填写动态参数")
                };
                
                const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`,{
                    attr_name:this.addParameList.attr_name,
                    attr_sel:this.addParameList.attr_sel
                });
                console.log(res)
                if (res.meta.status != 201) {
                    return this.$message.error('添加动态参数失败');
                }
				this.$message.success("添加动态参数成功");
				// 关闭对话框
				this.addParameter = false;
				// 重新获取
				this.getParamsData();
            })
        },
        //添加静态参数
        staticaddParameters(){
            this.$refs.staticaddParamsRef.validate(async valid =>{
                if (!valid) {
                    return this.$message.error("未填写静态参数")
                };
                
                const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`,{
                    attr_name:this.staticaddParameList.attr_name,
                    attr_sel:this.staticaddParameList.attr_sel
                });
                console.log(res)
                if (res.meta.status != 201) {
                    return this.$message.error('添加静态参数失败');
                }
				this.$message.success("添加静态参数成功");
				// 关闭对话框
				this.staticaddParameter = false;
				// 重新获取
				this.getParamsData();
            })
        },
        //编辑动态参数发送请求
        async selectParams(id){
            const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`,{
                attr_sel:"many",
            })
            if(res.meta.status !== 200){
                return this.$message.error("查询动态参数失败");
            }
            console.log(res)
            this.modifyParams=true;
            this.modifyForm=res.data;
        },
        //编辑动态参数提交请求
        modifyParamsInfo(){
            this.$refs.modifyParamsRef.validate(async valid => {
                //判断状态
                if(!valid){
                    return this.$message.error("修改动态参数失败");
                }
                const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.modifyForm.attr_id}`,{
                    attr_name:this.modifyForm.attr_name,
                    attr_sel:this.modifyForm.attr_sel,
                    attr_vals:this.modifyForm.attr_vals
                })
                console.log(res)
                //判断数据是否请求道
                if (res.meta.status!== 200) {
                    return this.$message.error('修改动态参数失败');
                }
                // 关闭对话框
                this.modifyParams = false;
                this.getParamsData();
                this.$message.success('修改动态参数成功');
            })
        },
        //编辑静态参数发送请求
        async staticSelectParams(id){
            const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`,{
                attr_sel:"only",
            })
            if(res.meta.status !== 200){
                return this.$message.error("查询静态参数失败");
            }
            console.log(res)
            this.staticmodifyParams=true;
            this.staticmodifyForm=res.data;
        },
        //编辑静态参数提交请求
        staticmodifyParamsInfo(){
            this.$refs.staticmodifyParamsRef.validate(async valid => {
                //判断状态
                if(!valid){
                    return this.$message.error("修改静态参数失败");
                }
                const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.staticmodifyForm.attr_id}`,{
                    attr_name:this.staticmodifyForm.attr_name,
                    attr_sel:this.staticmodifyForm.attr_sel,
                    attr_vals:this.staticmodifyForm.attr_vals
                })
                console.log(res)
                //判断数据是否请求道
                if (res.meta.status!== 200) {
                    return this.$message.error('修改静态参数失败');
                }
                // 关闭对话框
                this.staticmodifyParams = false;
                this.getParamsData();
                this.$message.success('修改静态参数成功');
            })
        },
        //删除动态
        removeParams(id) {
            this.$confirm("确定要删除该权限吗", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
            .then(async () => {
                const {data:res} = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
                if(res.meta.status != 200){
                    return this.$message.error('删除动态失败')
                }
                this.$message.success("删除成功!");
                this.getParamsData();
            })
            .catch(() => {
                this.$message.info("已取消删除!");
            });
            
        }, 
        //删除静态
        staticremoveParams(id) {
            this.$confirm("确定要删除该权限吗", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
            .then(async () => {
                const {data:res} = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
                if(res.meta.status != 200){
                    return this.$message.error('删除静态失败')
                }
                this.$message.success("删除成功!");
                this.getParamsData();
            })
            .catch(() => {
                this.$message.info("已取消删除!");
            });
            
        },         
    },
    computed: {
        cateId:function(){
            return this.selectedKeys.length === 3 ? this.selectedKeys[2] : null
        },
        btnDisabled:function(){
            return this.selectedKeys.length ===3 ? false : true
        }
    },
}
</script>
<style lang="less">
.cate-select{
    margin: 15px 0;
}
.el-tag{
    margin:10px;
}
</style>